package com.music.note_android.ui.folder

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.music.note_android.data.model.Folder
import com.music.note_android.data.model.Note
import com.music.note_android.data.repository.FolderRepository
import com.music.note_android.data.repository.NoteRepository
import com.music.note_android.data.repository.ValidationResult
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 文件夹管理ViewModel
 * 处理文件夹相关的业务逻辑
 */
@HiltViewModel
class FolderManagementViewModel @Inject constructor(
    private val folderRepository: FolderRepository,
    private val noteRepository: NoteRepository
) : ViewModel() {
    
    // UI状态
    private val _uiState = MutableStateFlow(FolderManagementUiState())
    val uiState: StateFlow<FolderManagementUiState> = _uiState.asStateFlow()
    
    // 文件夹列表
    val folders: StateFlow<List<Folder>> = folderRepository.getFoldersWithNoteCountFlow()
        .catch { exception ->
            _uiState.update { it.copy(error = exception.message) }
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = emptyList()
        )
    
    // 所有笔记列表（用于移动笔记功能）
    private val _allNotes = MutableLiveData<List<Note>>()
    val allNotes: LiveData<List<Note>> = _allNotes
    
    /**
     * 加载文件夹列表
     */
    fun loadFolders() {
        // folders已经通过StateFlow自动加载，这里可以用于手动刷新
    }
    
    /**
     * 加载所有笔记
     */
    fun loadAllNotes() {
        viewModelScope.launch {
            try {
                noteRepository.getAllNotes().collect { notes ->
                    _allNotes.value = notes
                }
            } catch (e: Exception) {
                _uiState.update { it.copy(error = e.message) }
            }
        }
    }
    
    /**
     * 创建新文件夹
     */
    fun createFolder(name: String) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            folderRepository.createFolder(name)
                .onSuccess {
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            message = "文件夹创建成功"
                        )
                    }
                }
                .onFailure { exception ->
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            error = exception.message ?: "创建文件夹失败"
                        )
                    }
                }
        }
    }
    
    /**
     * 重命名文件夹
     */
    fun renameFolder(folderId: String, newName: String) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            folderRepository.renameFolder(folderId, newName)
                .onSuccess {
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            message = "文件夹重命名成功"
                        )
                    }
                }
                .onFailure { exception ->
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            error = exception.message ?: "重命名文件夹失败"
                        )
                    }
                }
        }
    }
    
    /**
     * 删除文件夹
     */
    fun deleteFolder(folderId: String) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            folderRepository.deleteFolder(folderId)
                .onSuccess {
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            message = "文件夹删除成功"
                        )
                    }
                }
                .onFailure { exception ->
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            error = exception.message ?: "删除文件夹失败"
                        )
                    }
                }
        }
    }
    
    /**
     * 移动笔记到文件夹
     */
    fun moveNoteToFolder(noteId: String, folderId: String?) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            folderRepository.moveNoteToFolder(noteId, folderId)
                .onSuccess {
                    val folderName = if (folderId == null) "未分类" else "文件夹"
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            message = "笔记已移动到${folderName}"
                        )
                    }
                }
                .onFailure { exception ->
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            error = exception.message ?: "移动笔记失败"
                        )
                    }
                }
        }
    }
    
    /**
     * 批量移动笔记到文件夹
     */
    fun moveNotesToFolder(noteIds: List<String>, folderId: String?) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            folderRepository.moveNotesToFolder(noteIds, folderId)
                .onSuccess {
                    val folderName = if (folderId == null) "未分类" else "文件夹"
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            message = "已将${noteIds.size}个笔记移动到${folderName}"
                        )
                    }
                }
                .onFailure { exception ->
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            error = exception.message ?: "批量移动笔记失败"
                        )
                    }
                }
        }
    }
    
    /**
     * 验证文件夹名称
     */
    suspend fun validateFolderName(name: String, excludeId: String? = null): ValidationResult {
        return folderRepository.validateFolderName(name, excludeId)
    }
    
    /**
     * 检查文件夹是否可以删除
     */
    suspend fun canDeleteFolder(folderId: String): Boolean {
        return folderRepository.canDeleteFolder(folderId)
    }
    
    /**
     * 清除错误信息
     */
    fun clearError() {
        _uiState.update { it.copy(error = null) }
    }
    
    /**
     * 清除消息
     */
    fun clearMessage() {
        _uiState.update { it.copy(message = null) }
    }
    
    /**
     * 获取文件夹详情
     */
    fun getFolderById(folderId: String): Flow<Folder?> = flow {
        emit(folderRepository.getFolderById(folderId))
    }.catch { exception ->
        _uiState.update { it.copy(error = exception.message) }
        emit(null)
    }
}

/**
 * 文件夹管理UI状态
 */
data class FolderManagementUiState(
    val isLoading: Boolean = false,
    val error: String? = null,
    val message: String? = null
)